package global

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	"github.com/olivere/elastic/v7"
	"github.com/redis/go-redis/v9"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
)

func init() {
	ConsulInit()
	ViperInit()
	MysqlInit()
	RedisInit()
	EsInit()
}
func ConsulInit() {
	ConsulConf := api.DefaultConfig()
	ConsulConf.Address = "127.0.0.1:8500"
	ConsulClient, err := api.NewClient(ConsulConf)
	if err != nil {
		panic(err)
	}
	service := &api.AgentServiceRegistration{
		ID:      "shang",
		Name:    "shang",
		Tags:    []string{"xin"},
		Port:    1111,
		Address: "10.2.171.126",
		Check: &api.AgentServiceCheck{
			Interval: "3s",
			GRPC:     "10.2.171.126:1111",
		},
	}
	ConsulClient.Agent().ServiceRegister(service)
}
func ViperInit() {
	path := "D:/gos/src/four/zy/zg_four/server/dev.yaml"
	viper.SetConfigFile(path)
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	MysqlConfig.Username = viper.GetString("MysqlConf.Username")
	MysqlConfig.Password = viper.GetString("MysqlConf.Password")
	MysqlConfig.Host = viper.GetString("MysqlConf.Host")
	MysqlConfig.Port = viper.GetString("MysqlConf.Port")
	RedisConfig.Host = viper.GetString("RedisConf.Host")
	RedisConfig.Port = viper.GetString("RedisConf.Port")
	EsConfig.Host = viper.GetString("EsConf.Host")
	EsConfig.Port = viper.GetString("EsConf.Port")
}
func MysqlInit() {
	var err error
	dsn := MysqlConfig.Username + ":" + MysqlConfig.Password + "@tcp(" + MysqlConfig.Host + MysqlConfig.Port +
		")/xin?charset=utf8mb4&parseTime=True&loc=Local"
	fmt.Printf(dsn, "++++")
	MysqlDB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Println("数据库连接失败", err)
		return
	}
	log.Println("数据库连接success")
}
func RedisInit() {
	Redis = redis.NewClient(&redis.Options{
		Addr: RedisConfig.Host + RedisConfig.Port,
		DB:   0,
	})
}
func EsInit() {
	var err error
	dsn := "http://" + EsConfig.Host + EsConfig.Port
	EsClient, err = elastic.NewClient(elastic.SetURL(dsn), elastic.SetSniff(false))
	if err != nil {
		log.Println("es连接失败", err)
		return
	}
	log.Println("es连接success")
}
